import os
import comtypes.client

def docx_to_pdf(input_path, output_path):
    # 创建 Word 应用程序对象
    word = comtypes.client.CreateObject('Word.Application')
    word.Visible = False  # 不显示 Word 界面

    try:
        # 打开 .docx 文件
        doc = word.Documents.Open(input_path)
        # 保存为 .pdf 文件
        doc.SaveAs(output_path, FileFormat=17)  # 17 是 wdFormatPDF 的值
        # 关闭文档
        doc.Close()
    except Exception as e:
        print(f"Error converting {input_path} to PDF: {e}")
    finally:
        # 退出 Word 应用程序
        word.Quit()

def convert_docx_in_directory(directory):
    # 遍历目录
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.docx'):
                input_path = os.path.join(root, file)
                output_path = os.path.splitext(input_path)[0] + '.pdf'
                docx_to_pdf(input_path, output_path)
                print(f"Converted {input_path} to {output_path}")

if __name__ == "__main__":
    directory_path = r'D:\work\e\gjb\电子手册阅读器及编辑软件-2024\new\电子手册研发资料'  # 替换为你的目录路径
    convert_docx_in_directory(directory_path)